package com.bw.controller.linkman;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.entity.customer.PiCustomer;
import com.bw.entity.linkMan.Linkman;
import com.bw.resp.ResponseResult;
import com.bw.service.linkman.ILinkmanService;
import com.bw.utils.excel.ExcelUtil;
import com.bw.utils.idwork.IdWorker;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.excelutils.ExcelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xingjinning
 * @since 2020-06-15
 */
@RestController
@RequestMapping("/linkMan")
public class LinkmanController {

    @Autowired
    private ILinkmanService linkmanService;

    @Autowired
    private IdWorker idWorker;

    private final Logger log= LoggerFactory.getLogger(LinkmanController.class);

    /**
     * 列表  分页  模糊
     * @param pagenum
     * @param pagesize
     * @param linkman
     * @return
     */
    @PostMapping("/list/{pagenum}/{pagesize}")
    public ResponseResult list(@PathVariable("pagenum")int pagenum, @PathVariable("pagesize")int pagesize, @RequestBody Linkman linkman){
        log.info("开始查询列表");
        ResponseResult result = ResponseResult.SUCCESS();
        QueryWrapper queryWrapper = new QueryWrapper();
        PageHelper.startPage(pagenum,pagesize);
        try {
            if(linkman.getName()!=null){
                queryWrapper.like("name",linkman.getName());
            }
            if(linkman.getTel()!=null){
                queryWrapper.like("tel",linkman.getTel());
            }
            if(linkman.getPosition()!=null){
                queryWrapper.like("position",linkman.getPosition());
            }
            List list = linkmanService.list(queryWrapper);
            PageInfo pageInfo = new PageInfo(list);
            result.setResult(pageInfo);
        }catch (Exception e){
            log.error("查询错误"+e.toString());
            result.setSuccess(false);
            result.setMessage("查询失败"+e.toString());
        }
        log.info("查询结束");
        return result;
    }


    @GetMapping("getList/{id}")
    public ResponseResult getList(@PathVariable("id") Long id) {
        log.info("查询单个客户信息");
        ResponseResult result = ResponseResult.SUCCESS();

        try {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("customerId",id);
            List<Linkman> list = linkmanService.list(queryWrapper);
            result.setResult(list);
        } catch (Exception e) {
            log.error("查询单个失败"+e.toString());
            result.setSuccess(false);
            result.setMessage("获取失败" + e.toString());
        }
        log.info("查询单个客户信息结束");
        return result;
    }


    /**
     * 添加联系人
     * @param linkman
     * @return
     */
    @PostMapping("/addMan")
    public ResponseResult addMan( @RequestBody Linkman linkman){
        log.info("开始添加");
        ResponseResult result = ResponseResult.SUCCESS();

        try {

           linkmanService.saveOrUpdate(linkman);
            result.setMessage("操作成功");
        }catch (Exception e){
            log.error("添加错误"+e.toString());
            result.setSuccess(false);
            result.setMessage("操作失败"+e.toString());
        }
        log.info("结束添加");
        return result;
    }

    /**
     * 根据id删除联系人
     * @param id
     * @return
     */
    @PostMapping("/delMan/{id}")
    public ResponseResult delMan(@PathVariable("id")long id){
        log.info("开始删除");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            linkmanService.removeById(id);
            result.setMessage("删除成功");
        }catch (Exception e){
            log.error("删除失败"+e.toString());
            result.setSuccess(false);
            result.setMessage("删除失败"+e.toString());
        }
        log.info("结束删除");
        return result;
    }

    /**
     * 根据id查询联系人
     * @param id
     * @return
     */
    @PostMapping("/getMan/{id}")
    public ResponseResult getMan(@PathVariable("id")long id){
        log.info("开始根据id查询");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            Linkman linkman = linkmanService.getById(id);
            result.setMessage("查询成功");
            result.setResult(linkman);
        }catch (Exception e){
            log.error("查询失败"+e.toString());
            result.setSuccess(false);
            result.setMessage("添加失败"+e.toString());
        }
        log.info("结束根据id查询");
        return result;
    }

    /**
     * 导入
     * @param file
     * @return
     */
    @PostMapping("importExcel")
    public ResponseResult upload(MultipartFile file) {
        log.info("导入开始");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            //1，获取文件后缀
            String ext=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),file.getOriginalFilename().length());
            List<Map> mapList = ExcelUtil.readExcel(ext, file.getInputStream());
            String jsonStr = JSON.toJSONString(mapList);//mao集合转成json字符串
            List<Linkman> linkmen=JSON.parseArray(jsonStr,Linkman.class);//json字符串转成list对象集合
            linkmanService.saveBatch(linkmen);
        } catch (Exception e) {
            log.error("导入失败"+e.toString());
            result.setSuccess(false);
            result.setMessage("上传失败:" + e.toString());
        }
        log.info("导入结束");
        return result;
    }
//    @GetMapping("exportExcel")
//    public void exportExcel(HttpServletResponse response) throws IOException {
//        List<Linkman> linkmanList = linkmanService.list();
//        Workbook wb = new XSSFWorkbook();
//        Sheet sheet = wb.createSheet("联系人数据");
//        Row rowTitle = sheet.createRow(0);
//        String[] titles={"编号","姓名","性别","电话号码","邮箱","收件地址","职位","描述","客户id"};
//        Font font = wb.createFont();
//        font.setBold(true);
//        CellStyle cellStyle = wb.createCellStyle();
//        cellStyle.setFont(font);
//        for (int i=0;i<titles.length;i++){
//            Cell titleCell = rowTitle.createCell(i);
//            titleCell.setCellStyle(cellStyle);
//            titleCell.setCellValue(titles[i]);
//        }
//        for(int i=0;i<linkmanList.size();i++){
//            Row row = sheet.createRow(i + 1);
//            row.createCell(0).setCellValue(linkmanList.get(i).getId());
//            row.createCell(1).setCellValue(linkmanList.get(i).getName());
//            row.createCell(2).setCellValue(linkmanList.get(i).getSex());
//            row.createCell(3).setCellValue(linkmanList.get(i).getTel());
//            row.createCell(4).setCellValue(linkmanList.get(i).getEmail());
//            row.createCell(5).setCellValue(linkmanList.get(i).getRecvAddress());
//            row.createCell(6).setCellValue(linkmanList.get(i).getPosition());
//            row.createCell(7).setCellValue(linkmanList.get(i).getRemarks());
//            row.createCell(8).setCellValue(linkmanList.get(i).getCustomerId());
//
//        }
//        response.setHeader("Content-Type","application/vnd.ms-excel;charset=UTF-8");
//        response.setHeader("Content-Disposition","attachment;filename="+new String("联系人数据".getBytes(),"iso-8859-1")+".xlsx");
//        wb.write(response.getOutputStream());
//
//    }

    /**
     * 导出
     * @param response
     * @throws Exception
     */
    @GetMapping("exportExcel")
    public void exportExcel(HttpServletResponse response) throws Exception {
        log.info("开始导出");
        List<Linkman> linkmanList = linkmanService.list();
        response.setHeader("Content-Type","application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+new String("联系人数据".getBytes(),"iso-8859-1")+".xls");
        ClassPathResource classPathResource = new ClassPathResource("xls/linkman.xls");
        InputStream inputStream = classPathResource.getInputStream();
        ExcelUtils.addValue("list",linkmanList);
        ExcelUtils.export(inputStream,ExcelUtils.getContext(),response.getOutputStream());
        log.info("结束导出");
    }
}
